package myweb

import (
	"log"
	"main/myInterface"
	"net/http"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true // 允许跨域请求，仅用于开发环境
		},
	}
	clients    = make(map[*websocket.Conn]bool) // 已连接的客户端集合
	clientsMu  sync.Mutex                       // 客户端集合的互斥锁
	broadcast  = make(chan []byte)              // 广播消息通道
	closeChans = make(map[*websocket.Conn]chan struct{})
)

func wsHandler(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer conn.Close()

	clientsMu.Lock()
	clients[conn] = true
	closeChan := make(chan struct{})
	closeChans[conn] = closeChan
	clientsMu.Unlock()

	go writePump(conn, closeChan)
	readPump(conn)
}

func readPump(conn *websocket.Conn) {
	defer func() {
		clientsMu.Lock()
		delete(clients, conn)
		close(closeChans[conn])
		delete(closeChans, conn)
		clientsMu.Unlock()
	}()

	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("received: %s", message)
		myInterface.SerialWriteChan <- message
	}
}

func writePump(conn *websocket.Conn, closeChan chan struct{}) {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		// case b := <-myInterface.SerilBufChan:
		// 	if len(b) > 0 {
		// 		log.Printf("write: %s\n", string(b))
		// 		err := conn.WriteMessage(websocket.BinaryMessage, b)
		// 		if err != nil {
		// 			log.Println("write:", err)
		// 			return
		// 		}
		// 	}
		case b := <-myInterface.ChartsChan:
			if len(b) > 0 {
				log.Printf("title: %s\n", string(b))
				// err := conn.WriteMessage(websocket.BinaryMessage, b)
				// if err != nil {
				// 	log.Println("write:", err)
				// 	return
				// }
				for client := range clients {
					client.WriteMessage(websocket.BinaryMessage, b)
				}
			}
		case <-ticker.C:
			// 心跳检测或者其他周期性任务
		case <-closeChan:
			return
		}
	}
}

func broadcastHandler() {
	for {
		message := <-broadcast
		clientsMu.Lock()
		for client := range clients {
			client.WriteMessage(websocket.TextMessage, message)
		}
		clientsMu.Unlock()
	}
}

// // webSocket请求
// func wsHandler(c *gin.Context) {
// 	var (
// 		connFlag bool = false
// 	)

// 	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
// 	connList = append(connList, conn)
// 	if err != nil {
// 		log.Print("upgrade:", err)
// 		return
// 	}
// 	defer conn.Close()

// 	// 启动线程，不断发消息
// 	go func() {
// 		for {
// 			select {
// 			case b := <-myInterface.SerilBufChan:
// 				if len(b) > 0 {
// 					log.Printf("write: %s\n", string(b))
// 					err = conn.WriteMessage(websocket.BinaryMessage, b) //字节流方式发送
// 					if err != nil {
// 						log.Println("write:", err)
// 					}
// 				}
// 			case b := <-myInterface.TitleChan:
// 				if len(b) > 0 {
// 					fmt.Printf("title: %s\n", string(b))
// 					err = conn.WriteMessage(websocket.BinaryMessage, b)
// 					if err != nil {
// 						log.Println("write:", err)
// 					}
// 				}
// 			default:

// 			}
// 			if connFlag {
// 				connFlag = false
// 				log.Println("web socket closed")
// 				break
// 			}
// 		}
// 	}()

// 	for {
// 		messageType, message, err := conn.ReadMessage()
// 		if err != nil {
// 			log.Println("read:", err)
// 			connFlag = true
// 			break
// 		}
// 		log.Printf("received:%d %s", messageType, message)
// 		myInterface.SerialWriteChan <- message
// 	}
// }
